﻿using System;
using System.Collections.Generic;
using System.Data;
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http;
using FERROU8API.Pub;
using U8Login;
using UFIDA.U8.MomServiceCommon;
using UFSoft.U8.Framework.ContextSrv;
using UFSoft.U8.Framework.DBConnection;
using System.Text;

namespace FERROU8API.Plugin
{
    /// <summary>
    /// 采购入库单
    /// </summary>
    public class Rd01PLMPlugin
    {
        //private readonly string _ip = ConfigurationManager.AppSettings["WmsIP"] + "Moorderapi";
        public static string constr = "";
        private string url = "";

      
         
        public bool Update_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {
                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;
                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "Rd01PlmPlugin，Update_After，获取连接串失败";
                    DebugWriteLog.WriteLine("Rd01PlmPlugin", "Update_After", errMsg);
                    return false;
                }
                
                string accid = login.get_cAcc_Id();
                MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");
              
                string ccode = tmphead.attributes.getNamedItem("ccode").nodeValue.ObjToString();//入库单号
                string id = tmphead.attributes.getNamedItem("id").nodeValue.ObjToString();//入库单ID

                String js;
                js = GetCustJs(accid, ccode, id, 0);
                //不是线边仓直接返回true
                if (js == null)
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<PlmRequest>(result);
                if (apiresult.SUC_FLG != 0)
                {
                    errMsg = apiresult.Error_Message;
                    DebugWriteLog.WriteLine("Rd01PlmPlugin", "Update_After", errMsg);
                    throw new Exception(errMsg);
                }               

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("Rd01PlmPlugin", "Update_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

        private String GetCustJs(string accid, string ccode, string id, int operation)
        {
            DebugWriteLog.WriteLine("采购入库单插件", "ccode", "ccode=" + ccode + ";id=" + id);

            try
            {
                var datatable = Common.GetPlmUrl(constr, accid).Tables[0];
                       
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("采购入库单插件", "GetUrl", "Nopermission");
                    return null;
                }
                var datarow = datatable.Rows[0];
                
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("采购入库单插件", "GetUrl", "datarow Nopermission");
                    return null;
                }
                url = datarow[1].ObjToString() + "SY_MaterialPrice?";           
                
                
                #region SQL代码片段

                //inv.cInvStd 成品规格
                string sql = @"select a.cinvcode,
                            a.cfree1, a.cfree2, a.cfree3, a.ioritaxcost,
                            b.cexch_name, v.cvenname
                          from  rdrecords01 a with (nolock)
                           inner join rdrecord01 b with (nolock) on b.id = a.id
                           inner join vendor v with (nolock) on v.cvencode = b.cvencode     
                           where b.id = " + id ;

                var table = DbHelperSQL.Query(sql, constr, null).Tables[0];
                if (table == null || table.Rows.Count <= 0)
                {
                    DebugWriteLog.WriteLine("采购入库单插件", "table", " Nopermission");
                    return null;
                }
                #endregion

                string modids = string.Empty;

                List<plmrds01> mlist = new List<plmrds01>();
                foreach (DataRow item in table.Rows)
                {
                    #region mes原有字段
                    plmrds01 rd = new plmrds01();
                    rd.item_id = item["cinvcode"].ObjToString(); //物料条码
                    rd.qz2cz = item["cfree1"].ObjToString(); //材质  
                    rd.qz2gys = item["cvenname"].ObjToString(); //供应商名称
                    rd.qz2bz = item["cexch_name"].ObjToString(); //币种
                    rd.qz2cgj = item["ioritaxcost"].ObjToDecimal();//含税单价 
                    rd.orgcode = accid;

                    
                
                    #endregion

                    mlist.Add(rd);
                }
                DebugWriteLog.WriteLine("采购入库单插件PLM地址:" + url);
                DebugWriteLog.WriteLine("采购入库单插件", "获取列表", mlist.ToJson());
               
                ApiRequest req = new ApiRequest();
                req.data = mlist;
                req.orgcode = accid;
                req.primarykey = id.ToString();
                req.operation = operation;

                DebugWriteLog.WriteLine("采购入库单插件", "抛出参数", req.ToJson());
                return req.ToJson();
            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("采购入库单插件", "异常", e);
                throw e;
            }
        }

    }
}